package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 李旭
 * @date 2021/11/26 14:35
 * @Description:
 *
 *   用户微服务
 *
 */
@RestController
@RequestMapping("/api/user/passport")
public class UserInfoApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //提交登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){

        //1:用户名不能为空
        //2:密码不能为空


        //3:校验 用户或密码是否正确
        userInfo = userInfoService.login(userInfo);
        if(null == userInfo){
            return Result.fail().message("用户名或密码不正确");
        }else{
            //3.1正确 //回显   昵称|令牌   JWT:头 载荷 加密  字符串
            String token = UUID.randomUUID().toString();
            //3.2:将用户信息保存到Redis  方便以后网关的全局过滤器来进行校验
             // Redis: K:token V：用户ID
            redisTemplate.opsForValue().set(
                    RedisConst.USER_LOGIN_KEY_PREFIX + token,userInfo.getId().toString(),
                    RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

            //3.3返回
            Map map = new HashMap<>();
            map.put("token",token);
            map.put("nickName",userInfo.getNickName());
            return Result.ok(map);
        }
    }
    //查询收货地址
    @GetMapping("/findUserAddressList")
    public List<UserAddress> findUserAddressList(HttpServletRequest request){
        //真实用户
        String userId = AuthContextHolder.getUserId(request);

        return userInfoService.findUserAddressList(userId);
    }
}
